<?php

namespace Wintel\ApiBundle\Controller;

use Symfony\Component\Config\Definition\Exception\Exception;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;

class GroupController extends BaseController
{
    /**
     * @param Request $request
     * @return JsonResponse
     * 添加业务组
     */
    public function addAction(Request $request)
    {
        $conn = $this->get("doctrine.dbal.default_connection");
        $vccCode =  $this->getVccCode();
        $groupName = $request->get('group_name', 0);
        $winIp = $this->container->get('icsoc_core.common.class')->newGetWinIp();//通信服务器IP
        $port = $this->container->getParameter('win_socket_port');

        //vcc_code 验证
        $msg = $vid = $this->get('validator.custom')->checkVccCode($vccCode);
        if (!empty($msg) && is_array($msg)) {
            return new JsonResponse($msg);
        }

        //验证业务组是否存在
        $res = $this->getDoctrine()->getManager()
               ->getRepository("IcsocSecurityBundle:WinGroup")
               ->existGroupName($vid, $groupName, '');
        if ($res) {
            $msg = array(
                'code' => '403',
                'message' => '业务组名称已存在'
            );
            return new JsonResponse($msg);
        }

        $data = array(
            'vcc_id' => $vid,
            'group_name' => $groupName,
        );
        try {
            $conn->insert('win_group', $data);
            //插入成功之后；重载业务组；
            $ret = $this->get('validator.custom')->wintelsReload($vid, $winIp, $port, 406);
            return new JsonResponse($ret);
        } catch (Exception $e) {
            $ret = array(
                'code' => 405,
                'message' => '添加业务组失败['.$e->getMessage().']'
            );
            return new JsonResponse($ret);
        }
    }

    /**
     * @param Request $request
     * @return JsonResponse
     * 编辑业务组
     */
    public function updateAction(Request $request)
    {
        $conn = $this->get("doctrine.dbal.default_connection");
        $vcc_code =  $this->getVccCode();
        $groupId = $request->get('group_id', 0);
        $groupName = $request->get('group_name', '');

        $winIp = $this->container->get('icsoc_core.common.class')->newGetWinIp();//通信服务器IP
        $port = $this->container->getParameter('win_socket_port');

        //vcc_code 验证
        $msg = $vid = $this->get('validator.custom')->checkVccCode($vcc_code);
        if (!empty($msg) && is_array($msg)) {
            return new JsonResponse($msg);
        }

        //验证业务组是否存在
        $res = $this->getDoctrine()->getManager()
            ->getRepository("IcsocSecurityBundle:WinGroup")
            ->existGroupName($vid, $groupName, $groupId);
        if ($res) {
            $msg = array(
                'code' => '403',
                'message' => '业务组名称已存在'
            );
            return new JsonResponse($msg);
        }

        //开始修改入库
        $data = array(
            'vcc_id' => $vid,
            'group_name' => $groupName,
        );
        try {
            $conn->update('win_group', $data, array('vcc_id'=>$vid, 'group_id'=>$groupId));
            $ret = $this->get('validator.custom')->wintelsReload($vid, $winIp, $port, 406);
            return new JsonResponse($ret);
        } catch (Exception $e) {
            $ret = array(
                'code' => 407,
                'message' => '编辑业务组失败['.$e->getMessage().']'
            );
            return new JsonResponse($ret);
        }
    }

    /**
     * @param $vcc_code
     * @param $group_id
     * @return JsonResponse
     * 删除业务组
     */
    public function deleteAction(Request $request)
    {
        //vcc_code 验证
        /** @var \Doctrine\DBAL\Connection $conn */
        $conn = $this->get("doctrine.dbal.default_connection");
        $winIp = $this->container->get('icsoc_core.common.class')->newGetWinIp();//通信服务器IP
        $port = $this->container->getParameter('win_socket_port');
        $group_id = $request->get('group_id', '');
        $vcc_code = $this->getVccCode();
        $msg = $vid = $this->get('validator.custom')->checkVccCode($vcc_code);
        if (!empty($msg) && is_array($msg)) {
            return new JsonResponse($msg);
        }

        //有批量删除情况
        $group_arr = json_decode($group_id);
        $group_arr = json_last_error() || !is_array($group_arr) ? array((int)$group_id) : $group_arr;
        if (empty($group_arr)) {
            return new JsonResponse(array('code'=>408, 'message'=>'业务组id为空'));
        }

        $errorMsg = array();
        foreach ($group_arr as $id) {
            try {
                $conn->update('win_group', array('is_del'=>1), array('vcc_id'=>$vid, 'group_id'=>$id));
                //重载业务组；
                $ret = $this->get('validator.custom')->wintelsReload($vid, $winIp, $port, 406);
                $errorMsg[] = array_merge($ret, array('group_id'=>$id));
            } catch (Exception $e) {
                $errorMsg[] = array(
                    'code' => 405,
                    'message' => '删除业务组失败['.$e->getMessage().']',
                    'group_id' => $id
                );
            }
        }
        return new JsonResponse(array('code'=>500,'message'=>'总结果','data'=>$errorMsg));
    }

    /**
     * @param $vcc_code
     * @param $info
     * @return JsonResponse
     * 获得业务组列表
     */

    public function listAction(Request $request)
    {
        $conn = $this->get("doctrine.dbal.default_connection");
        $vcc_code = $this->getVccCode();
        $info = $request->get('info', '');
        $msg = $vid = $this->get('validator.custom')->checkVccCode($vcc_code);
        if (!empty($msg) && is_array($msg)) {
            return new JsonResponse($msg);
        }

        //分页搜索相关信息；
        $addInfo = array();
        if (!empty($info)) {
            $addInfo = json_decode($info, true);
            if (json_last_error()) {
                return new JsonResponse(array('code' => 404, 'message'=>'info格式非json'));
            }
        }
        $where = '';
        if (isset($addInfo['filter'])) {
            if (isset($addInfo['filter']['que_id'])) {
                //验证业务组是否属于该企业
                $msg = $this->get('validator.custom')->vccGroup($vid, $addInfo['filter']['group_id'], 403);
                if (!empty($msg)) {
                    return new JsonResponse($msg);
                }

            }
            $where = isset($addInfo['filter']['group_id']) && !empty($addInfo['filter']['group_id']) ? " AND w.group_id = '".(int)$addInfo['filter']['group_id']."'" : '';
            $where.= isset($addInfo['filter']['group_name']) && !empty($addInfo['filter']['group_name']) ? " AND group_name like '%".$addInfo['filter']['group_name']."%'" : '';
        }
        $count = $conn->fetchColumn(
            'SELECT count(*) '.
            'FROM win_group as w '.
            'WHERE vcc_id = :vcc_id AND is_del = 0 '.$where,
            array('vcc_id'=>$vid)
        );
        $page = $this->get("validator.extend.custom")->getPageInfo($count, 'win_group', $addInfo);
        $page['sort'] = $page['sort'] !=1 ? 'w.'.$page['sort'] : $page['sort'];
        $list = $conn->fetchAll(
            'SELECT group_name,group_id '.
            'FROM win_group w '.
            'WHERE w.vcc_id = :vcc_id AND w.is_del = 0 '.$where.
            'ORDER BY '.$page['sort'].' '.$page['order'].' LIMIT '.$page['start'].','.$page['limit'],
            array('vcc_id'=>$vid)
        );
        $ret = array(
            'code' => 200,
            'message' =>'ok',
            'total' => $count,
            'data' => $list,
        );
        return new JsonResponse($ret);
    }

    /**
     * 坐席分配或取消到业务组
     * @param Request $request
     * @return JsonResponse
     */
    public function agentAssignAction(Request $request)
    {
        $params['group_id'] = $request->get('group_id', 0);
        $agentIds = $request->get('agent_ids', '');
        $params['ids']  = empty($agentIds) ? array() : explode(",", $agentIds);
        $params['flag'] = $request->get('flag', 1);
        $vccCode = $this->getVccCode();
        $params['vcc_id'] = $this->get('doctrine.dbal.default_connection')->fetchColumn(
            "SELECT vcc_id FROM cc_ccods WHERE vcc_code = ? LIMIT 1",
            array($vccCode)
        );

        $ret = $this->get('icsoc_data.model.businessgroup')->allotAgentBusinessGroup($params);

        return new JsonResponse($ret);
    }

}
